package com.rainng.coursesystem.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rainng.coursesystem.base.api.dto.PagingReqDTO;
import com.rainng.coursesystem.dao.mapper.PlanMapper;
import com.rainng.coursesystem.model.entity.*;
import com.rainng.coursesystem.model.taskplan.PlanStateUpdateVo;
import com.rainng.coursesystem.model.taskplan.PlanUpdateVo;
import com.rainng.coursesystem.model.taskplan.PlanVo;
import com.rainng.coursesystem.model.taskplan.PlanProjectVo;
import com.rainng.coursesystem.model.taskplan.DeliveryVo;
import com.rainng.coursesystem.model.taskplan.ReturnVo;

import com.rainng.coursesystem.model.taskplan.CarVo;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.module.custom.mapper.CustomMapper;
import com.rainng.coursesystem.module.task.dto.request.CodeWhiteListDTO;
import com.rainng.coursesystem.module.task.dto.request.TaskCarDTO;
import com.rainng.coursesystem.module.task.dto.response.CodeWhiteListResDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class PlanService extends BaseService {

    @Resource
    private PlanMapper mapper;

    @Resource
    private UserService userService;

    @Resource
    private CustomMapper customMapper;

    @Transactional
    public ResultVO deletePlanById(String id){
        List<Map<String,Object>> res = mapper.getPlanDetailById(id);
        Map<String, Object> planDetail = res.get(0);
        String applyNum = (String) planDetail.get("applyNum");
        String vin = (String) planDetail.get("vin");
        mapper.deleteProjectsById(applyNum);
        mapper.deleteCarByVin(vin);
        int i = mapper.deletePlanById(id);
        return result("删除成功");
    }

    public ResultVO getPlanDetailById(String id){
        List<Map<String,Object>> res = mapper.getPlanDetailById(id);
        if (res.size() > 0){
            return result(res.get(0));
        }
        return result(new HashMap<>());
    }



    public ResultVO getTaskInfoByTaskCode(String taskcode){

        List<Map<String,Object>> res = mapper.selectInfoByTaskCode(taskcode);
        if (res.size() > 0){
            return result(res.get(0));
        }

        return result(new HashMap<>());
    }


    public ResultVO saveTaskPlan(PlanVo vo){
        Date date = new Date();
        long thistime = date.getTime();
        int i = mapper.savePlan(vo,thistime);
        if (vo.getPlanType().equals(1)) {
            PlanProjectVo projectVo = new PlanProjectVo();
            projectVo.setConfigs(vo.getConfigs());
            projectVo.setApplyNum(vo.getApplyNum());
            projectVo.setId(vo.getTrialId());
            int carNum = 1;
            projectVo.setCarNum(carNum);
            mapper.saveTrialProjects(projectVo);
            // 存入车辆表
            CarVo carVo = new CarVo();
            carVo.setVin(vo.getVin());
            carVo.setTaskCode(vo.getTaskCode());
            carVo.setConfigId(vo.getTrialId());
            carVo.setVeType(vo.getVeType());
            carVo.setTire(vo.getTire());
            carVo.setStatus(0);
            carVo.setAllConfigIndex(0);
            mapper.saveCar(carVo);
            // 自动生成一条流转记录. 负责人: 主检
            DeliveryVo deliveryVo = new DeliveryVo();
            deliveryVo.setDeliveryDate(vo.getArriveTime());
            deliveryVo.setTransferDestination(vo.getArriveAddress());
            deliveryVo.setResponsiblePerson(vo.getUserName());
            deliveryVo.setPlannedRecipient(vo.getPlannedRecipient());
            deliveryVo.setPlanId(vo.getTrialId());
            deliveryVo.setStatus(0);
            mapper.saveDeliveryRecord(deliveryVo, thistime);
        }
        return result("新增成功");
    }



    public ResultVO updatePlan(PlanUpdateVo vo){

        int i = mapper.updatePlan(vo);
        PlanProjectVo projectVo = new PlanProjectVo();
        projectVo.setConfigs(vo.getConfigs());
        projectVo.setApplyNum(vo.getApplyNum());
        mapper.updateProjects(projectVo);
        CarVo carVo = new CarVo();
        carVo.setVin(vo.getVin());
        carVo.setTire(vo.getTire());
        mapper.updateCar(carVo);
        return result("修改成功");
    }

    public ResultVO updatePlanState(PlanStateUpdateVo vo){

        int i = mapper.updatePlanState(vo);

        return result("修改成功");
    }
    public TrialProjectNumEntity getTrialProject(String applyNum){

        return mapper.getTrialProject(applyNum);
    }

    //增加权限 6 场地可见自身
    public ResultVO countPlan(PlanVo po) {
        ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
        String username = vo.getData().get("username");
        String userId = String.valueOf(vo.getData().get("uId"));
        String userType = String.valueOf(vo.getData().get("userType"));
        if ("1".equals(userType) || "2".equals(userType)) {
            po.setUserId(userId);
        }
//        if ("7".equals(userType)) {
//            //根据查询企业
//            String uname = vo.getData().get("username");
//            if(StrUtil.isNotEmpty(uname)){
//                List<String> c = customMapper.getCompanyNameByUserName(uname);
//                if(c.size() > 0){
//                    po.setComName(c.get(0));
//                }
//            }else{
//                po.setComName(" ");
//            }
//        }
        int i = mapper.countPlan(po);
        return result(i);
    }

    public List<Object> selectPlan(PlanVo po) {
        Page<Object> pageParam = new Page<>(po.getPageNum(), po.getPageSize());
        ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
        String username = vo.getData().get("username");
        String userId = String.valueOf(vo.getData().get("uId"));
        String userType = String.valueOf(vo.getData().get("userType"));
        if ("1".equals(userType) || "2".equals(userType)) {
            po.setUserId(userId);
        }
        if ("7".equals(userType)) {
            //根据查询企业
            String uname = vo.getData().get("username");
            if(StrUtil.isNotEmpty(uname)){
                List<String> c = customMapper.getCompanyNameByUserName(uname);
                if(c.size() > 0){
                    po.setComName(c.get(0));
                }
            }else{
                po.setComName(" ");
            }
        }


        IPage<Object> o = mapper.queryPlan(po, pageParam);
        if (o == null) {
            return new ArrayList<>();
        }
        return o.getRecords();
    }
    public List<TireInfoEntity> getTireList(String vin) {
        List<TireInfoEntity> res;
        res = mapper.getTireList(vin);
        return res;
    }
    public IPage<TakePhotoItemsEntity> getPhotoItems(PagingReqDTO<TakePhotoItemsEntity> reqDTO) {
        IPage<TakePhotoItemsEntity> res;
        res = mapper.getPhotoItems(reqDTO.toPage(), reqDTO.getParams());
        return res;
    }
    public ResultVO saveTakePhotosItems(TakePhotoItemsEntity reqDto) {
        mapper.saveTakePhotosItems(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public ResultVO deleteTakePhotosItems(TakePhotoItemsEntity reqDto) {
        mapper.deleteTakePhotosItems(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public ResultVO updateTakePhotosItems(TakePhotoItemsEntity reqDto) {
        mapper.updateTakePhotosItems(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public List<TrialProjectsEntity> getTrialProjectsByUserId(String userId, String vin) {
        List<TrialProjectsEntity> res;
        res = mapper.getTrialProjectsByUserId(userId, vin);
        return res;
    }
    public List<TakePhotoItemsEntity> getTrialPhotosItems(String prjNum) {
        List<TakePhotoItemsEntity> res;
        res = mapper.getTrialPhotosItems(prjNum);
        return res;
    }
    public List<TakePhotoItemsEntity> getNormalTrialPhotosItems(String prjNum) {
        List<TakePhotoItemsEntity> res;
        res = mapper.getNormalTrialPhotosItems(prjNum);
        return res;
    }
    public ResultVO getDeliveryLocation(){
        List<Map<String,Object>> res = mapper.getDeliveryLocation();
        if (res.size() > 0){
            return result(res);
        }
        return result(new HashMap<>());
    }
    public ResultVO saveDeliveryRecord(DeliveryVo reqDto) {
        Date date = new Date();

        long thistime = date.getTime();
        reqDto.setStatus(0);
        mapper.saveDeliveryRecord(reqDto, thistime);
        String flowStatus = "在途";
        String planId = reqDto.getPlanId();
        mapper.updatePlanFlowStatus(flowStatus, planId);
        return result("新增成功");
    }
    public ResultVO updateDelivery(DeliveryVo vo){
        mapper.updateDelivery(vo);
        return result("更新成功");
    }
    public ResultVO deleteDelivery(DeliveryVo vo){
        mapper.deleteDelivery(vo.getId());
        return result("删除成功");
    }
    public List<DeliveryVo> queryDeliveryRecord(String planId) {
        List<DeliveryVo> res;
        res = mapper.queryDeliveryRecord(planId);
        return res;
    }
    public ResultVO updateDeliveryRecord(DeliveryVo vo){

        int i = mapper.updateDeliveryRecord(vo);
        String flowStatus = vo.getTransferDestination();
        String planId = vo.getPlanId();
        mapper.updatePlanFlowStatus(flowStatus, planId);
        return result("更新成功");
    }
    public ResultVO saveReturnRecord(ReturnVo reqDto) {
        Date date = new Date();

        long thistime = date.getTime();
        mapper.saveReturnRecord(reqDto, thistime);
        return result("新增成功");
    }
    public ResultVO updateReturnRecord(ReturnVo reqDto) {
        mapper.updateReturnRecord(reqDto);
        return result("更新成功");
    }
    public List<ReturnVo> queryReturnRecord(String planId) {
        List<ReturnVo> res;
        res = mapper.queryReturnRecord(planId);
        return res;
    }
    public ResultVO deleteReturn(DeliveryVo vo){
        mapper.deleteReturn(vo.getId());
        return result("删除成功");
    }
    public ResultVO updateCarByVin(TaskCarDTO vo){
        mapper.updateCarByVin(vo);
        return result("更新成功");
    }
    public ResultVO getCarConfig(String vin){
        TaskCarDTO res = mapper.getCarConfig(vin);
        return result(res);
    }
    public ResultVO cleanAllFlow(Integer planId){
        mapper.cleanFlowRecord(planId);
        mapper.cleanReturnRecord(planId);
        mapper.resetPlanState(planId);
        return result("删除成功");
    }
}
